#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "thread.h"

// 容器
#define MAX_FISH 10
int fish_num = 0;

// 锁住鱼数量的锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

// 捕鱼完成
pthread_cond_t cond_add_fish = PTHREAD_COND_INITIALIZER;

// 吃鱼完成
pthread_cond_t cond_eat_fish = PTHREAD_COND_INITIALIZER;

void *fishman_impl(void *arg)
{
    pthread_t tid = pthread_self();
    while (1)
    {
        pthread_mutex_lock(&mutex);
        while (fish_num == MAX_FISH)
        {
            printf("渔夫(%ld):容器满了,等小猫吃鱼\n", tid);
            // 容器已满 要让猫吃鱼
            pthread_cond_wait(&cond_eat_fish, &mutex);
            // 松开锁给其他线程，并且本线程在这里一直等到cond_eat_fish的信号
        }
        fish_num++;
        printf("渔夫(%ld):捕获了一条鱼；现在鱼的数量有%d条\n", tid, fish_num);
        pthread_cond_signal(&cond_add_fish); // 发送捕鱼完成信号给小猫
        sleep(rand() % 3);
        pthread_mutex_unlock(&mutex);
    }
}

void *cat_impl(void *arg)
{
    pthread_t tid = pthread_self();
    while (1)
    {
        pthread_mutex_lock(&mutex);
        while (fish_num == 0)
        {
            // 容器空了
            printf("猫(%ld)：没鱼了，等老头捕鱼\n", tid);
            pthread_cond_wait(&cond_add_fish, &mutex);
            // 松开锁给其他线程，并且本线程在这里一直等到cond_add_fish的信号
        }
        fish_num--;
        printf("猫(%ld)：吃了一条鱼:现在鱼的数量有%d条\n", tid, fish_num);
        // pthread_cond_signal(&cond_eat_fish); // 发送吃鱼完成信号给老头
        pthread_cond_broadcast(&cond_eat_fish); // 发送吃鱼完成信号给老头
        sleep(rand() % 3);
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{

    create(fishman_impl, NULL);
    create(fishman_impl, NULL);
    create(fishman_impl, NULL);
    create(cat_impl, NULL);
    create(cat_impl, NULL);
    create(cat_impl, NULL);
    create(cat_impl, NULL);
    create(cat_impl, NULL);
    // printf("fishman id1:%d fishman_id2:%d,cat id:%d\n", fishman_id1, fishman_id2, cat_id);
    // join();
}